/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;


import dto_pakinfo.Profile;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLStreamException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author Thinh
 */
public class XMLUtil {

    public static void marshalObject(JAXBContext context, Object object, String pathFile) throws JAXBException, IOException, XMLStreamException {
        Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
//        marshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

        File file = new File(pathFile);
        if (!file.exists()) {
            System.out.println("File not foud");
            file.createNewFile();
        }
        System.out.println("File  found");

        marshaller.marshal(object, file);
    
    }

    public static String marshalObject(JAXBContext context, Object object, OutputStream os) throws JAXBException, IOException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StringUtil.encoding);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        marshaller.marshal(object, os);
        return os.toString();
    }

    public static String generateCheckoutXML(Profile profile, String customCartXML, String confirmation) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(Profile.class);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        marshalObject(context, profile, out);
        String profileXML = out.toString("UTF-8");

        profileXML = profileXML.trim();
        int index = profileXML.lastIndexOf("?>");
        if(index != -1) {
            profileXML = profileXML.substring(index + 2).trim();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<order>");
        sb.append(profileXML);
        sb.append(customCartXML);
        sb.append("<confirmation>");
        sb.append(confirmation);
        sb.append("</confirmation>");
        sb.append("</order>");
        return sb.toString();
    }

    public static void methodTrAX(String xslPath, String xmlString, String output) throws TransformerConfigurationException, FileNotFoundException, TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        StreamSource xsltFile = new StreamSource(xslPath);
        Transformer trans = tf.newTransformer(xsltFile);
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        StreamSource xmlFile = new StreamSource(new StringReader(xmlString));
        StreamResult htmlFile = new StreamResult(new FileOutputStream(output));
        trans.transform(xmlFile, htmlFile);
    }

    public static Object unmarshalObject(JAXBContext context, String filePath) throws JAXBException {
        Unmarshaller u = context.createUnmarshaller();

//        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//        Schema schema = sf.newSchema(new File(schemaFilePath));
//
//        u.setSchema(schema);

        File f = new File(filePath);
        return u.unmarshal(f);
    }

    public static Object unmarshallObject(JAXBContext context, String filePath, String schemaFilePath) throws JAXBException, SAXException {
        Unmarshaller u = context.createUnmarshaller();
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(schemaFilePath));

        u.setSchema(schema);

        File f = new File(filePath);
        return u.unmarshal(f);
    }

    public static Object unmarshalObject(JAXBContext context, String filePath, StringReader sr, String schemaFilePath) throws JAXBException, SAXException {
        Unmarshaller u = context.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(schemaFilePath));

        u.setSchema(schema);

        File f = new File(filePath);
        return u.unmarshal(f);
    }

    public static Object unmarshalObject(JAXBContext context, StringReader sr) throws JAXBException {
        Unmarshaller u = context.createUnmarshaller();
        return u.unmarshal(sr);

    }

    public static Object unmarshallObject(JAXBContext context, Document doc, String schemaFilePath) throws JAXBException, SAXException {
        Unmarshaller u = context.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(schemaFilePath));

        u.setSchema(schema);
        return u.unmarshal(doc);
    }

    public static Object unmarshallObject(JAXBContext context, Document doc) throws JAXBException, SAXException {
        Unmarshaller u = context.createUnmarshaller();

        return u.unmarshal(doc);
    }

    public static java.sql.Date convertToSqlDate(java.util.Date oDate) {
        return (new java.sql.Date(oDate.getTime()));
    }

    /**
     * Returns the util.Date for the given sql.Date
     *
     * @param sqlDate sql.Date object
     * @return util.Date
     */
    public static java.util.Date convertToDate(java.sql.Date sqlDate) {
        return (new java.util.Date(sqlDate.getTime()));
    }

    /**
     * Parse an xml file to dom.
     * @param filepath
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public static Document parserDOMXML(String filepath) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File file = new File(filepath);
        Document doc = db.parse(file);

        return doc;
    }

    /**
     * Write DOM to xml file.
     * @param node
     * @param filePath
     * @throws TransformerConfigurationException
     * @throws TransformerException
     */
    public static void writeXML(Node node, String filePath) throws TransformerConfigurationException, TransformerException, IOException {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer trans = tff.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setParameter("encoding", "UTF-8");
        Source src = new DOMSource(node);

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
        trans.transform(src, new StreamResult(out));
        System.out.println("============ Write DOM successfully ===========");
    }

    /**
     * Write inputStream to XML
     * @param inputStream
     * @param filePath
     * @throws TransformerConfigurationException
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     * @throws TransformerException
     */
    public static void writeXML(InputStream inputStream, String filePath) throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException, TransformerException {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer trans = tff.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setParameter(OutputKeys.ENCODING, StringUtil.encoding);
        trans.setParameter("encoding", StringUtil.encoding);

        Source src = new StreamSource(inputStream);

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), StringUtil.encoding));
        trans.transform(src, new StreamResult(out));
        System.out.println("============ Write DOM successfully ===========");
    }
}
